import { createSlice, type PayloadAction } from '@reduxjs/toolkit'

// 定义用户信息类型
interface UserInfo {
  username: string
  role: number
  userId: number
  token: string
}

// 定义用户状态类型
interface UserState {
  isLoggedIn: boolean
  userInfo: UserInfo | null
  isLoading: boolean
  error: string | null
}

// 初始状态
const initialState: UserState = {
  isLoggedIn: false,
  userInfo: null,
  isLoading: false,
  error: null,
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // 设置加载状态
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.isLoading = action.payload
    },
    
    // 登录成功
    loginSuccess: (state, action: PayloadAction<UserInfo>) => {
      state.isLoggedIn = true
      state.userInfo = action.payload
      state.isLoading = false
      state.error = null
    },
    
    // 登录失败
    loginFailure: (state, action: PayloadAction<string>) => {
      state.isLoggedIn = false
      state.userInfo = null
      state.isLoading = false
      state.error = action.payload
    },
    
    // 登出
    logout: (state) => {
      state.isLoggedIn = false
      state.userInfo = null
      state.isLoading = false
      state.error = null
    },
    
    // 清除错误信息
    clearError: (state) => {
      state.error = null
    },
    
    // 从localStorage恢复用户状态
    restoreUserState: (state, action: PayloadAction<UserInfo>) => {
      state.isLoggedIn = true
      state.userInfo = action.payload
      state.isLoading = false
      state.error = null
    },
  },
})

// 导出actions
export const {
  setLoading,
  loginSuccess,
  loginFailure,
  logout,
  clearError,
  restoreUserState,
} = userSlice.actions

export default userSlice.reducer
